package com.liu.wode.controller;

import com.liu.wode.mapper.DepartmentMapper;
import com.liu.wode.mapper.EmployeeMapper;
import com.liu.wode.pojo.Department;
import com.liu.wode.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Controller
public class EmployeeController {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DepartmentMapper departmentMapper;

    @RequestMapping("/myEmps")
    public String queryEmpList(Model model){
        List<Employee> employees = employeeMapper.queryEmployeeList();
        model.addAttribute("emps",employees);
        return "emp/list";
    }

    @GetMapping("/EtoAdd")
    public String toAddEmp(Model model){
        List<Department> departments = departmentMapper.queryDepartmentList();
        model.addAttribute("departments",departments);
        return "emp/add";
    }

    @PostMapping("/EtoAdd")
    public String addEmp(@RequestParam("name") String name, @RequestParam("department") String department, @RequestParam("entrydate") Date entrydate){
        int init=0;
        while (employeeMapper.queryEmployeeById(init)!=null){
            init++;
        }
        employeeMapper.addEmployee(new Employee(init,name,department,entrydate));
        return "redirect:/myEmps";
    }

    @GetMapping("/delemp/{id}")
    public String delUser(@PathVariable("id") Integer id){
        employeeMapper.delEmployee(id);
        return "redirect:/myEmps";
    }

    @GetMapping("/emp/{id}")
    public String toUpdateUser(@PathVariable("id")Integer id,Model model){
        Employee employee = employeeMapper.queryEmployeeById(id);
        List<Department> departments = departmentMapper.queryDepartmentList();
        model.addAttribute("emp",employee);
        model.addAttribute("departments",departments);
        return "emp/update";
    }
    @PostMapping("/updateEmp")
    public String updateEmp(Employee employee){
        employeeMapper.upEmployee(employee);
        return "redirect:/myEmps";
    }

}
